import { getPretreatmentRecordChannelList } from '@/services/api/api-datahub-record';
import { Button, Spin } from 'antd';
import { values } from 'lodash';
import React, { useEffect, useState } from 'react';
import './CheckboxRadio.less';
interface ChannelProps {
  vlaues?: string[];
  onChange: (values: string[]) => void;
}
const ChannelCheckboxRadio: React.FC<ChannelProps> = ({ vlaues, onChange }) => {
  const [selectedButtons, setSelectedButtons] = useState<string[]>([]);
  const [channelList, setChannelList] = useState<CuesTopicData.ChannelList[]>([]);

  const handleButtonClick = (buttonKey: string) => {
    if (selectedButtons.includes(buttonKey)) {
      setSelectedButtons(selectedButtons.filter((key) => key !== buttonKey));
      onChange(selectedButtons.filter((key) => key !== buttonKey));
    } else {
      setSelectedButtons([...selectedButtons, buttonKey]);
      onChange([...selectedButtons, buttonKey]);
    }
  };

  const getChannelList = async () => {
    const res = await getPretreatmentRecordChannelList();
    setChannelList(res.data);
  };

  useEffect(() => {
    getChannelList();
  }, []);

  useEffect(() => {
    setSelectedButtons(vlaues);
  }, [vlaues]);

  return (
    <>
      <Spin
        spinning={channelList && channelList.length <= 0}
      >
        {channelList && channelList.length > 0 && <>
          <Button
            key=""
            onClick={() => {
              setSelectedButtons([]), onChange([]);
            }}
            className={`first ${selectedButtons.length === 0 ? 'selected' : ''}`}
          >
            全部
          </Button>
          {channelList.slice(0, channelList.length - 1).map((item) => (
            <Button
              key={item.id}
              onClick={() => handleButtonClick(item.id)}
              className={`center ${selectedButtons.includes(item.id) ? 'selected' : ''}`}
            >
              {item.name}
            </Button>
          ))}
          <Button
            key={channelList[channelList?.length - 1]?.id}
            onClick={() => handleButtonClick(channelList[channelList?.length - 1]?.id)}
            className={`end ${selectedButtons.includes(channelList[channelList?.length - 1]?.id) ? 'selected' : ''
              }`}
          >
            {channelList[channelList?.length - 1]?.name}
          </Button>
        </>
        }

      </Spin >
    </>
  );
};

export default ChannelCheckboxRadio;
